package com.venn.controller;


import com.venn.entity.User;
import com.venn.service.UserService;
import com.venn.service.imp.UserServiceImp;
import com.venn.util.MD5Utils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.List;

/**
 *
 */
@Controller
@RequestMapping("/user")
public class UserController {

	private static Logger logger = LogManager.getLogger(UserController.class.getName());

	@Autowired
	private UserService userService; //= new UserServiceImp();


	@RequestMapping(value = "/login")
	public String login(@RequestParam("username") String username, @RequestParam("password") String password,HttpSession session) {

		System.out.println("loginName =" + username);
		System.out.println("password =" + password);
		logger.info("md5 pares password :" + password);
		password = MD5Utils.getMD5(password);
		User user = new User(username,password);
		String id = userService.userLogin(user);
		// if id is -1, user|pass error
		if (id != null) {
			user.setId(id);
			logger.info("put user : "+username +" to session");
			session.putValue("user",user);
			logger.info(username + " login success");
			return "home";
		}
		return "../index";
	}

	@RequestMapping(value = "/signup", method = RequestMethod.POST)
	public String signUp(@RequestParam("cloginName") String loginName, @RequestParam("cpassword") String password,HttpSession session) {

		System.out.println("loginName =" + loginName);
		System.out.println("password =" + password);

		if (userService.signUp(loginName,password)) {

			session.putValue("user",loginName);
			logger.info(loginName + " sign up success");
		}

		return "home";
	}

	@RequestMapping(value = "/queryAll", method = RequestMethod.GET)
	public String queryAll() {

		List<User> users = userService.queryAll();

		return "userList";
	}
	@RequestMapping(value = "/deleteUser" ,method = RequestMethod.POST)
	public String deleteUser(@RequestParam("id")String id){
		userService.deleteUser(id);
		// forword to queryAll method
		return "forward:/user/queryAll";
	}
	@RequestMapping(value = "/deleteUsers" ,method = RequestMethod.POST)
	public String deleteUserBatch(@RequestParam("ids")String[]ids){
		userService.deleteUserBatch(Arrays.asList(ids));
		// forword to queryAll method
		return "forward:/user/queryAll";
	}

	public String modifyUser(@RequestParam("user") User user){

		userService.modifyUser(user);
		return "";

	}



}
